<!DOCTYPE html>
<html>
<head>
    <title>Stripe 支付测试</title>
    <script src="https://js.stripe.com/v3/"></script>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            max-width: 800px; 
            margin: 50px auto; 
            padding: 20px; 
        }
        .section {
            background: #f8f9fa;
            padding: 20px;
            margin: 20px 0;
            border-radius: 8px;
            border: 1px solid #dee2e6;
        }
        .section h2 {
            margin-top: 0;
            color: #495057;
        }
        #card-element { 
            padding: 15px; 
            border: 1px solid #ccc; 
            border-radius: 4px; 
            margin: 10px 0; 
        }
        button { 
            background: #5469d4; 
            color: white; 
            border: none; 
            padding: 12px 20px; 
            border-radius: 4px; 
            cursor: pointer; 
            font-size: 16px; 
            width: 100%;
            margin: 5px 0;
        }
        button.subscription { background: #28a745; }
        button.cancel { background: #dc3545; }
        button:disabled { background: #ccc; }
        .result { 
            margin-top: 20px; 
            padding: 15px; 
            border-radius: 4px; 
        }
        .success { 
            background: #d4edda; 
            color: #155724; 
            border: 1px solid #c3e6cb; 
        }
        .error { 
            background: #f8d7da; 
            color: #721c24; 
            border: 1px solid #f5c6cb; 
        }
        .loading { color: #6c757d; }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="number"], input[type="text"], select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .subscription-item {
            background: white;
            padding: 15px;
            margin: 10px 0;
            border-radius: 4px;
            border: 1px solid #ccc;
        }
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }
        .status-active { background: #d4edda; color: #155724; }
        .status-trialing { background: #d1ecf1; color: #0c5460; }
        .status-canceled { background: #f8d7da; color: #721c24; }
        .status-past_due { background: #fff3cd; color: #856404; }
    </style>
</head>
<body>
    <h1>🔥 Stripe 支付测试系统</h1>
    <p><strong>测试环境</strong> - 使用测试卡号，不会产生真实费用</p>
    <p><strong>🌐 跨域支持</strong> - 此API支持从任何域名访问（CORS已配置）</p>
    
    <!-- 一次性支付部分 -->
    <div class="section">
        <h2>💳 一次性支付</h2>
        <form id="payment-form">
            <div class="form-group">
                <label for="amount">💰 金额（分）:</label>
                <input type="number" id="amount" value="2000" min="100" placeholder="例如：2000 = $20.00">
            </div>
            
            <div class="form-group">
                <label for="user-id">👤 用户ID:</label>
                <input type="text" id="user-id" value="2" placeholder="输入用户ID">
            </div>
            
            <div class="form-group">
                <label for="card-element">💳 信用卡信息:</label>
                <div id="card-element">
                    <!-- Stripe Elements 会在这里创建卡片输入框 -->
                </div>
            </div>
            
            <button id="submit-button">💳 立即支付</button>
        </form>
    </div>

    <!-- 订阅支付部分 -->
    <div class="section">
        <h2>🔄 订阅支付</h2>
        <div class="form-group">
            <label for="subscription-user-id">👤 用户ID:</label>
            <input type="text" id="subscription-user-id" value="2" placeholder="输入用户ID">
        </div>
        
        <div class="form-group">
            <label for="subscription-plan">📋 订阅计划:</label>
            <select id="subscription-plan">
                <option value="price_1RTdIJ04wlOsEYrBxwXtA5k0">基础月费计划 - $9.99/月</option>
                <option value="price_1RTdIK04wlOsEYrB1Oa7ou6n">专业月费计划 - $19.99/月</option>
                <option value="price_1RTdIL04wlOsEYrB3ElsNCIK">企业月费计划 - $99.99/月</option>
                <option value="price_1RTdIM04wlOsEYrBbMBLcdFF">基础年费计划 - $95.99/年</option>
            </select>
        </div>
        
        <div class="form-group">
            <label for="trial-days">🆓 试用天数:</label>
            <input type="number" id="trial-days" value="7" min="0" max="30" placeholder="试用期天数（可选）">
        </div>
        
        <button id="create-subscription-button" class="subscription">🎯 创建订阅</button>
        <button id="load-subscriptions-button" class="subscription">📋 查看用户订阅</button>
    </div>

    <!-- 订阅管理部分 -->
    <div class="section">
        <h2>📊 订阅管理</h2>
        <div id="subscriptions-list">
            <p>点击"查看用户订阅"加载订阅列表...</p>
        </div>
    </div>
    
    <div id="result"></div>

    <div style="margin-top: 30px; padding: 15px; background: #f8f9fa; border-radius: 4px;">
        <h3>🧪 测试卡号</h3>
        <ul>
            <li><strong>成功支付:</strong> 4242 4242 4242 4242</li>
            <li><strong>被拒绝:</strong> 4000 0000 0000 0002</li>
            <li><strong>需要认证:</strong> 4000 0025 0000 3155</li>
            <li><strong>余额不足:</strong> 4000 0000 0000 9995</li>
        </ul>
        <p><em>过期日期：任何未来日期，CVC：任何3位数字</em></p>
        
        <h3>💡 测试价格ID说明</h3>
        <ul>
            <li><strong>price_1RTdIJ04wlOsEYrBxwXtA5k0:</strong> 基础月费计划 - $9.99/月</li>
            <li><strong>price_1RTdIK04wlOsEYrB1Oa7ou6n:</strong> 专业月费计划 - $19.99/月</li>
            <li><strong>price_1RTdIL04wlOsEYrB3ElsNCIK:</strong> 企业月费计划 - $99.99/月</li>
            <li><strong>price_1RTdIM04wlOsEYrBbMBLcdFF:</strong> 基础年费计划 - $95.99/年</li>
        </ul>
        <p><em>注意：这些是真实的Stripe测试价格ID，可以正常使用</em></p>
    </div>

    <script>
        // 1. 初始化 Stripe（请替换为您的公钥）
        const stripe = Stripe('pk_test_51RSW2j04wlOsEYrByuTAfth7Ny7CKtKIHBkzUA9NxJQEsSpIsbB48kFlQBQNSrH4blMcCOhfCoGpcz7SPohgv5Pe002LGgGzsC');
        const elements = stripe.elements();
        
        // 2. 创建卡片元素
        const cardElement = elements.create('card', {
            style: {
                base: {
                    fontSize: '16px',
                    color: '#424770',
                    '::placeholder': {
                        color: '#aab7c4',
                    },
                },
            },
        });
        cardElement.mount('#card-element');

        // 3. 处理一次性支付表单
        document.getElementById('payment-form').addEventListener('submit', async (event) => {
            event.preventDefault();
            
            const submitButton = document.getElementById('submit-button');
            const resultDiv = document.getElementById('result');
            const amount = document.getElementById('amount').value;
            const userId = document.getElementById('user-id').value;
            
            submitButton.disabled = true;
            submitButton.textContent = '🔄 处理中...';
            resultDiv.innerHTML = '<div class="loading">⏳ 正在处理支付，请稍候...</div>';
            
            try {
                // 步骤1: 创建支付意图
                console.log('🚀 创建支付意图...');
                const response = await fetch('http://localhost:3379/api/payments/payment-intent', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        userId: userId,
                        amount: parseInt(amount),
                        currency: 'usd',
                        description: '测试支付',
                        allowRedirects: false
                    })
                });
                
                const paymentData = await response.json();
                console.log('💾 支付意图响应:', paymentData);
                
                if (!paymentData.success) {
                    throw new Error(paymentData.message);
                }
                
                // 步骤2: 前端确认支付
                console.log('🔐 确认支付...');
                const { error, paymentIntent } = await stripe.confirmCardPayment(
                    paymentData.data.clientSecret,
                    {
                        payment_method: {
                            card: cardElement,
                            billing_details: {
                                name: 'Test User',
                                email: 'test@example.com'
                            }
                        }
                    }
                );
                
                if (error) {
                    console.error('❌ 支付错误:', error);
                    resultDiv.innerHTML = `<div class="error">❌ 支付失败: ${error.message}</div>`;
                } else {
                    console.log('✅ 支付成功:', paymentIntent);
                    resultDiv.innerHTML = `
                        <div class="success">
                            <h3>🎉 支付成功！</h3>
                            <p><strong>支付ID:</strong> ${paymentIntent.id}</p>
                            <p><strong>状态:</strong> ${paymentIntent.status}</p>
                            <p><strong>金额:</strong> $${(paymentIntent.amount / 100).toFixed(2)}</p>
                            <p><strong>货币:</strong> ${paymentIntent.currency.toUpperCase()}</p>
                        </div>
                    `;
                }
                
            } catch (error) {
                console.error('💥 处理错误:', error);
                resultDiv.innerHTML = `<div class="error">💥 错误: ${error.message}</div>`;
            }
            
            submitButton.disabled = false;
            submitButton.textContent = '💳 立即支付';
        });

        // 4. 创建订阅
        document.getElementById('create-subscription-button').addEventListener('click', async () => {
            const button = document.getElementById('create-subscription-button');
            const resultDiv = document.getElementById('result');
            const userId = document.getElementById('subscription-user-id').value;
            const priceId = document.getElementById('subscription-plan').value;
            const trialDays = document.getElementById('trial-days').value;
            
            if (!userId || !priceId) {
                resultDiv.innerHTML = '<div class="error">❌ 请填写用户ID和选择订阅计划</div>';
                return;
            }
            
            button.disabled = true;
            button.textContent = '🔄 创建中...';
            resultDiv.innerHTML = '<div class="loading">⏳ 正在创建订阅...</div>';
            
            try {
                const response = await fetch('http://localhost:3379/api/payments/subscriptions', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        userId: userId,
                        priceId: priceId,
                        trialPeriodDays: parseInt(trialDays) || undefined,
                        metadata: {
                            source: 'payment-test-page'
                        }
                    })
                });
                
                const data = await response.json();
                console.log('📋 订阅创建响应:', data);
                
                if (data.success) {
                    // 如果需要支付确认
                    if (data.data.clientSecret) {
                        console.log('🔐 订阅需要支付确认...');
                        const { error, paymentIntent } = await stripe.confirmCardPayment(
                            data.data.clientSecret,
                            {
                                payment_method: {
                                    card: cardElement,
                                    billing_details: {
                                        name: 'Test User',
                                        email: 'test@example.com'
                                    }
                                }
                            }
                        );
                        
                        if (error) {
                            throw new Error(`支付确认失败: ${error.message}`);
                        }
                    }
                    
                    resultDiv.innerHTML = `
                        <div class="success">
                            <h3>🎉 订阅创建成功！</h3>
                            <p><strong>订阅ID:</strong> ${data.data.subscriptionId}</p>
                            <p><strong>状态:</strong> ${data.data.status}</p>
                            <p><strong>当前周期:</strong> ${new Date(data.data.currentPeriodStart * 1000).toLocaleDateString()} - ${new Date(data.data.currentPeriodEnd * 1000).toLocaleDateString()}</p>
                            ${data.data.trialStart ? `<p><strong>试用期:</strong> ${new Date(data.data.trialStart * 1000).toLocaleDateString()} - ${new Date(data.data.trialEnd * 1000).toLocaleDateString()}</p>` : ''}
                        </div>
                    `;
                    
                    // 自动刷新订阅列表
                    loadUserSubscriptions();
                } else {
                    throw new Error(data.message);
                }
                
            } catch (error) {
                console.error('💥 订阅创建错误:', error);
                resultDiv.innerHTML = `<div class="error">💥 订阅创建失败: ${error.message}</div>`;
            }
            
            button.disabled = false;
            button.textContent = '🎯 创建订阅';
        });

        // 5. 加载用户订阅
        async function loadUserSubscriptions() {
            const userId = document.getElementById('subscription-user-id').value;
            const subscriptionsDiv = document.getElementById('subscriptions-list');
            
            if (!userId) {
                subscriptionsDiv.innerHTML = '<p>请先输入用户ID</p>';
                return;
            }
            
            subscriptionsDiv.innerHTML = '<div class="loading">⏳ 加载订阅列表...</div>';
            
            try {
                const response = await fetch(`http://localhost:3379/api/payments/users/${userId}/subscriptions`);
                const data = await response.json();
                console.log('📋 用户订阅响应:', data);
                
                if (data.success) {
                    if (data.data.length === 0) {
                        subscriptionsDiv.innerHTML = '<p>用户暂无订阅</p>';
                    } else {
                        const subscriptionsHtml = data.data.map(sub => {
                            const statusClass = `status-${sub.status}`;
                            const currentPeriod = `${new Date(sub.currentPeriodStart).toLocaleDateString()} - ${new Date(sub.currentPeriodEnd).toLocaleDateString()}`;
                            const trial = sub.trialStart ? `<p><strong>试用期:</strong> ${new Date(sub.trialStart).toLocaleDateString()} - ${new Date(sub.trialEnd).toLocaleDateString()}</p>` : '';
                            
                            return `
                                <div class="subscription-item">
                                    <div style="display: flex; justify-content: space-between; align-items: center;">
                                        <div>
                                            <h4>${sub.stripeSubscriptionId}</h4>
                                            <span class="status-badge ${statusClass}">${sub.status}</span>
                                            <p><strong>价格ID:</strong> ${sub.stripePriceId}</p>
                                            <p><strong>当前周期:</strong> ${currentPeriod}</p>
                                            ${trial}
                                            ${sub.cancelAtPeriodEnd ? '<p><strong>⚠️ 将在周期结束时取消</strong></p>' : ''}
                                        </div>
                                        <div>
                                            ${sub.status === 'active' && !sub.cancelAtPeriodEnd ? 
                                                `<button class="cancel" onclick="cancelSubscription('${sub.stripeSubscriptionId}', true)">🚫 周期结束取消</button>
                                                 <button class="cancel" onclick="cancelSubscription('${sub.stripeSubscriptionId}', false)">⛔ 立即取消</button>` : 
                                                ''}
                                        </div>
                                    </div>
                                </div>
                            `;
                        }).join('');
                        
                        subscriptionsDiv.innerHTML = subscriptionsHtml;
                    }
                } else {
                    throw new Error(data.message);
                }
                
            } catch (error) {
                console.error('💥 加载订阅错误:', error);
                subscriptionsDiv.innerHTML = `<div class="error">💥 加载失败: ${error.message}</div>`;
            }
        }

        // 6. 取消订阅
        async function cancelSubscription(subscriptionId, cancelAtPeriodEnd = true) {
            const resultDiv = document.getElementById('result');
            
            if (!confirm(`确定要${cancelAtPeriodEnd ? '在周期结束时' : '立即'}取消订阅吗？`)) {
                return;
            }
            
            resultDiv.innerHTML = '<div class="loading">⏳ 正在取消订阅...</div>';
            
            try {
                const response = await fetch(`http://localhost:3379/api/payments/subscriptions/${subscriptionId}/cancel`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        cancelAtPeriodEnd: cancelAtPeriodEnd
                    })
                });
                
                const data = await response.json();
                console.log('🚫 取消订阅响应:', data);
                
                if (data.success) {
                    resultDiv.innerHTML = `
                        <div class="success">
                            <h3>✅ 订阅${cancelAtPeriodEnd ? '已标记为周期结束取消' : '已立即取消'}！</h3>
                            <p><strong>订阅ID:</strong> ${data.data.subscriptionId}</p>
                            <p><strong>状态:</strong> ${data.data.status}</p>
                            <p><strong>周期结束取消:</strong> ${data.data.cancelAtPeriodEnd ? '是' : '否'}</p>
                        </div>
                    `;
                    
                    // 自动刷新订阅列表
                    loadUserSubscriptions();
                } else {
                    throw new Error(data.message);
                }
                
            } catch (error) {
                console.error('💥 取消订阅错误:', error);
                resultDiv.innerHTML = `<div class="error">💥 取消失败: ${error.message}</div>`;
            }
        }

        // 7. 绑定查看订阅按钮
        document.getElementById('load-subscriptions-button').addEventListener('click', loadUserSubscriptions);
        
        // 8. 处理卡片输入错误
        cardElement.on('change', ({error}) => {
            const displayError = document.getElementById('result');
            if (error) {
                displayError.innerHTML = `<div class="error">⚠️ ${error.message}</div>`;
            } else {
                displayError.innerHTML = '';
            }
        });

        // 9. 页面加载完成提示
        window.addEventListener('load', () => {
            console.log('📱 Stripe 支付测试页面已加载');
            console.log('🔑 请确保后端服务运行在 http://localhost:3379');
            
            // 自动加载订阅列表（如果有用户ID）
            const userId = document.getElementById('subscription-user-id').value;
            if (userId) {
                loadUserSubscriptions();
            }
        });

        // 10. 全局函数，供HTML调用
        window.cancelSubscription = cancelSubscription;
    </script>
</body>
</html> 